<template>
  <div class="asset-transfer-container">
    <h2>资产流转报表</h2>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="资产编号">
          <el-input v-model="searchForm.assetCode" placeholder="请输入资产编号"></el-input>
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="searchForm.assetName" placeholder="请输入资产名称"></el-input>
        </el-form-item>
        <el-form-item label="流转类型">
          <el-select v-model="searchForm.transferType" placeholder="选择流转类型">
            <el-option label="转移" value="转移"></el-option>
            <el-option label="借用" value="借用"></el-option>
            <el-option label="归还" value="归还"></el-option>
            <el-option label="报废" value="报废"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="searchForm.operator" placeholder="请输入操作人"></el-input>
        </el-form-item>
        <el-form-item label="流转日期">
          <el-date-picker
            v-model="searchForm.transferDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button type="success" @click="exportReport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>流转类型分布</span>
          <el-select v-model="chartType" size="small" @change="initChart">
            <el-option label="饼图" value="pie"></el-option>
            <el-option label="柱状图" value="bar"></el-option>
          </el-select>
        </div>
      </template>
      <div ref="chartContainer" class="chart-container"></div>
    </el-card>
    
    <el-card class="table-card">
      <div class="table-header">
        <span>资产流转记录</span>
        <div class="header-actions">
          <el-radio-group v-model="chartType" size="small" @change="handleChartTypeChange">
            <el-radio-button label="pie">饼图</el-radio-button>
            <el-radio-button label="bar">柱状图</el-radio-button>
          </el-radio-group>
          <el-select v-model="dateRange" size="small" @change="handleDateRangeChange">
            <el-option label="近7天" value="7"></el-option>
            <el-option label="近30天" value="30"></el-option>
            <el-option label="近90天" value="90"></el-option>
            <el-option label="全部" value="all"></el-option>
          </el-select>
          <el-button type="primary" size="small" @click="handleExport">导出</el-button>
        </div>
      </div>
      <el-table :data="transferData" style="width: 100%" border>
        <el-table-column prop="assetCode" label="资产编号" width="150"></el-table-column>
        <el-table-column prop="assetName" label="资产名称"></el-table-column>
        <el-table-column prop="transferType" label="流转类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getTransferTypeTagType(scope.row.transferType)">{{ scope.row.transferType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fromDeptName" label="原部门" width="120"></el-table-column>
        <el-table-column prop="toDeptName" label="目标部门" width="120"></el-table-column>
        <el-table-column prop="fromUserName" label="原使用人" width="100"></el-table-column>
        <el-table-column prop="toUserName" label="新使用人" width="100"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="100"></el-table-column>
        <el-table-column prop="transferDate" label="流转日期" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.transferDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'AssetTransfer',
  setup() {
    const searchForm = ref({
      assetCode: '',
      assetName: '',
      transferType: '',
      operator: '',
      transferDate: ''
    })
    
    const chartContainer = ref(null)
    const chartInstance = ref(null)
    const chartType = ref('pie')
    const dateRange = ref('30')
    const transferData = ref([])
    const transferTypeStats = ref([])
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 获取资产流转数据
    const getAssetTransferData = async () => {
      try {
        const params = {
          ...searchForm.value,
          dateRange: dateRange.value === 'all' ? null : parseInt(dateRange.value),
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize
        }
        
        const response = await axios.get('/api/statistics/transfer', {
          params
        })
        
        if (response.code === 200 && response.data) {
          transferData.value = response.data.records || response.data
          pagination.value.total = response.data.total || 0
          
          // 获取流转类型统计数据
          if (response.data.typeStats) {
            transferTypeStats.value = response.data.typeStats
          } else {
            // 计算统计数据
            calculateTypeStats()
          }
          
          initChart()
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取资产流转数据失败:', error)
        setMockData()
      }
    }
    
    // 设置模拟数据
    const setMockData = () => {
      transferData.value = [
        {
          id: '1',
          assetCode: 'ZC2024001',
          assetName: '联想ThinkPad笔记本电脑',
          transferType: '转移',
          fromDeptName: '技术部',
          toDeptName: '市场部',
          fromUserName: '张三',
          toUserName: '李四',
          operator: '王五',
          transferDate: '2024-11-01 10:30:00',
          remark: '人员调动'
        },
        {
          id: '2',
          assetCode: 'ZC2024002',
          assetName: 'Dell显示器',
          transferType: '借用',
          fromDeptName: '行政部',
          toDeptName: '技术部',
          fromUserName: '',
          toUserName: '赵六',
          operator: '赵六',
          transferDate: '2024-10-28 14:20:00',
          remark: '项目需要'
        },
        {
          id: '3',
          assetCode: 'ZC2024003',
          assetName: 'HP激光打印机',
          transferType: '归还',
          fromDeptName: '市场部',
          toDeptName: '行政部',
          fromUserName: '钱七',
          toUserName: '',
          operator: '钱七',
          transferDate: '2024-10-25 09:15:00',
          remark: '临时借用结束'
        },
        {
          id: '4',
          assetCode: 'ZC2024006',
          assetName: '旧台式电脑',
          transferType: '报废',
          fromDeptName: '财务部',
          toDeptName: '',
          fromUserName: '孙八',
          toUserName: '',
          operator: '管理员',
          transferDate: '2024-10-20 16:30:00',
          remark: '设备老化'
        },
        {
          id: '5',
          assetCode: 'ZC2024004',
          assetName: '办公桌椅套装',
          transferType: '转移',
          fromDeptName: '人力资源部',
          toDeptName: '财务部',
          fromUserName: '王五',
          toUserName: '周九',
          operator: '管理员',
          transferDate: '2024-10-18 11:00:00',
          remark: '部门调整'
        }
      ]
      
      calculateTypeStats()
      initChart()
      pagination.value.total = 50 // 模拟总数
    }
    
    // 计算流转类型统计
    const calculateTypeStats = () => {
      const stats = {}
      transferData.value.forEach(item => {
        if (stats[item.transferType]) {
          stats[item.transferType]++
        } else {
          stats[item.transferType] = 1
        }
      })
      
      transferTypeStats.value = Object.keys(stats).map(key => ({
        name: key,
        value: stats[key]
      }))
    }
    
    // 初始化图表
    const initChart = () => {
      nextTick(() => {
        if (!chartContainer.value) return
        
        if (chartInstance.value) {
          chartInstance.value.dispose()
        }
        
        chartInstance.value = echarts.init(chartContainer.value)
        
        const option = generateChartOption()
        chartInstance.value.setOption(option)
        
        window.addEventListener('resize', handleResize)
      })
    }
    
    // 生成图表配置
    const generateChartOption = () => {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'],
        series: [{
          name: '流转类型',
          type: chartType.value,
          radius: chartType.value === 'pie' ? '60%' : 'auto',
          data: transferTypeStats.value,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {c}\n({d}%)'
          }
        }]
      }
      
      if (chartType.value === 'bar') {
        option.xAxis = {
          type: 'category',
          data: transferTypeStats.value.map(item => item.name)
        }
        option.yAxis = {
          type: 'value'
        }
        option.series[0].barWidth = '60%'
        option.series[0].label = {
          show: true,
          position: 'top'
        }
      }
      
      return option
    }
    
    // 获取流转类型标签类型
    const getTransferTypeTagType = (type) => {
      const typeMap = {
        '转移': 'primary',
        '借用': 'warning',
        '归还': 'success',
        '报废': 'danger'
      }
      return typeMap[type] || 'info'
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return ''
      const date = new Date(dateTimeStr)
      if (isNaN(date.getTime())) return dateTimeStr
      return date.toLocaleString('zh-CN')
    }
    
    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize()
      }
    }
    
    // 查询
    const search = () => {
      pagination.value.currentPage = 1
      getAssetTransferData()
    }
    
    // 重置
    const reset = () => {
      searchForm.value = {
        assetCode: '',
        assetName: '',
        transferType: '',
        operator: '',
        transferDate: ''
      }
      pagination.value.currentPage = 1
      getAssetTransferData()
    }
    
    // 导出报表
    const exportReport = () => {
      // 实际项目中这里可以调用后端导出接口
      console.log('导出资产流转报表')
      alert('资产流转报表导出成功')
    }
    
    // 处理日期范围变化
    const handleDateRangeChange = () => {
      pagination.value.currentPage = 1
      getAssetTransferData()
    }
    
    // 处理页码大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      getAssetTransferData()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      getAssetTransferData()
    }
    
    onMounted(() => {
      getAssetTransferData()
    })
    
    return {
      searchForm,
      chartContainer,
      chartType,
      dateRange,
      transferData,
      pagination,
      getTransferTypeTagType,
      formatDateTime,
      search,
      reset,
      exportReport,
      initChart,
      handleDateRangeChange,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.asset-transfer-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 20px;
  margin-right: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>